/**
 * 右下角通知弹窗组件
 */
(function($) {
    // 通知弹窗默认配置
    var defaultOptions = {
        position: 'fixed',
        bottom: '20px',
        right: '20px',
        width: '320px',
        zIndex: 9999,
        autoHideDelay: 5000, // 5秒后自动隐藏
        showAnimation: 'slideInUp',
        hideAnimation: 'slideOutDown',
        maxNotifications: 5, // 最多同时显示5个通知
        apiUrl: '', // 获取新通知的API
        checkInterval: 30000 // 30秒检查一次新通知
    };

    // 当前显示的通知列表
    var notifications = [];
    var lastCheckTime = new Date().getTime();
    var checkTimer;
    var audioInitialized = false;

    /**
     * 根据优先级获取样式类名
     * @param {Number} priority 优先级
     * @return {String} 样式类名
     */
    function getPriorityClass(priority) {
        var priorityClass = '';
        switch(priority) {
            case 5: // 立即 (danger)
                priorityClass = 'danger';
                break;
            case 4: // 紧急 (warning)
                priorityClass = 'warning';
                break;
            case 3: // 高 (primary)
                priorityClass = 'primary';
                break;
            case 2: // 中 (success)
                priorityClass = 'success';
                break;
            case 1: // 低 (info)
            default:
                priorityClass = 'info';
                break;
        }
        return priorityClass;
    }

    /**
     * 创建通知弹窗
     * @param {Object} options 配置选项
     */
    function createNotification(options) {
        var settings = $.extend({}, defaultOptions, options || {});
        
        // 限制同时显示的通知数量
        if (notifications.length >= settings.maxNotifications) {
            var oldNotification = notifications.shift();
            removeNotification(oldNotification.id);
        }
        
        var notificationId = 'notification-' + new Date().getTime();
        var notification = $('<div id="' + notificationId + '" class="notification-popup">' +
            '<div class="notification-header">' +
                '<span class="notification-title">' + (options.title || '系统通知') + '</span>' +
                '<button type="button" class="notification-close">&times;</button>' +
            '</div>' +
            '<div class="notification-content">' +
                (options.content || '您有新的通知消息') +
            '</div>' +
            '<div class="notification-footer">' +
                '<a href="javascript:;" class="notification-action">查看详情</a>' +
            '</div>' +
            '</div>');
        
        // 添加样式
        notification.css({
            position: settings.position,
            bottom: settings.bottom,
            right: settings.right,
            width: settings.width,
            zIndex: settings.zIndex
        });
        
        // 添加优先级样式类
        var priorityClass = getPriorityClass(options.priority);
        notification.addClass('notification-' + priorityClass);
        
        // 添加到页面
        $('body').append(notification);
        
        // 添加动画
        notification.addClass(settings.showAnimation);
        
        // 保存通知信息
        var notificationData = {
            id: notificationId,
            messageId: options.id || options.messageId, // 保存消息ID
            element: notification,
            url: options.url || '',
            priority: options.priority || 1, // 优先级，默认为低优先级(1)
            autoHide: options.autoHide !== undefined ? options.autoHide : true,
            delay: options.delay || settings.autoHideDelay
        };
        
        notifications.push(notificationData);
        
        // 绑定事件
        bindNotificationEvents(notificationData);
        
        // 自动隐藏
        if (notificationData.autoHide) {
            setTimeout(function() {
                removeNotification(notificationId);
            }, notificationData.delay);
        }
        
        return notificationData;
    }

    /**
     * 绑定通知事件
     * @param {Object} notificationData 通知数据
     */
    function bindNotificationEvents(notificationData) {
        var notification = notificationData.element;
        
        // 关闭按钮事件
        notification.find('.notification-close').on('click', function(e) {
            e.stopPropagation();
            removeNotification(notificationData.id);
        });
        
        // 点击通知内容区域跳转
        notification.find('.notification-action, .notification-content').on('click', function(e) {
            e.preventDefault();
            if (notificationData.url) {
                // 使用notificationData对象中的messageId字段作为消息ID
                var messageId = notificationData.messageId || notificationData.id;
                if (window.parent && window.parent.viewMessage && typeof window.parent.viewMessage === 'function') {
                    window.parent.viewMessage(messageId);
                } else if (typeof viewMessage === 'function') {
                    viewMessage(messageId);
                } else {
                    // 如果viewMessage函数不存在，则使用原来的跳转方式
                    if (notificationData.url.startsWith('http') || notificationData.url.includes('://')) {
                        window.open(notificationData.url, '_blank');
                    } else {
                        window.location.href = ctx + notificationData.url;
                    }
                }
                removeNotification(notificationData.id);
            }
        });
        
        // 鼠标悬停暂停自动隐藏
        notification.on('mouseenter', function() {
            // 可以在这里添加暂停自动隐藏的逻辑
        }).on('mouseleave', function() {
            // 可以在这里添加恢复自动隐藏的逻辑
        });
    }

    // 查看通知详情
    function viewMessage(messageId) {
        if (window.parent && window.parent.$) {
            window.parent.$.modal.openTab("通知详情", "/system/message/view/" + messageId);
        } else {
            $.modal.openTab("通知详情", "/system/message/view/" + messageId);
        }
    }

    /**
     * 移除通知
     * @param {String} notificationId 通知ID
     */
    function removeNotification(notificationId) {
        var notificationIndex = -1;
        for (var i = 0; i < notifications.length; i++) {
            if (notifications[i].id === notificationId) {
                notificationIndex = i;
                break;
            }
        }
        
        if (notificationIndex === -1) return;
        
        var notification = notifications[notificationIndex];
        var element = notification.element;
        
        // 添加隐藏动画
        element.addClass(defaultOptions.hideAnimation);
        
        // 动画完成后移除元素
        setTimeout(function() {
            element.remove();
        }, 500);
        
        // 从列表中移除
        notifications.splice(notificationIndex, 1);
    }

    /**
     * 检查新通知
     */
    function checkNewNotifications() {
        if (!defaultOptions.apiUrl) return;
        
        $.ajax({
            url: defaultOptions.apiUrl,
            type: 'GET',
            data: { lastCheckTime: lastCheckTime },
            success: function(response) {
                if (response && response.data && response.data.length > 0) {
                    var newNotifications = response.data;
                    for (var i = 0; i < newNotifications.length; i++) {
                        var notif = newNotifications[i];
                        createNotification({
                            id: notif.messageId,
                            title: notif.title,
                            content: notif.content,
                            url: notif.url,
                            priority: notif.priority,
                            autoHide: notif.autoHide !== false
                        });
                        
                        // 播放提示音
                        playNotificationSound();
                    }
                }
                lastCheckTime = new Date().getTime();
            }
        });
    }

    /**
     * 播放通知提示音
     */
    function playNotificationSound() {
        // 检查是否已经有全局音频对象
        if (typeof notificationAudio !== 'undefined' && notificationAudio) {
            notificationAudio.currentTime = 0;
            var playPromise = notificationAudio.play();
            
            if (playPromise !== undefined) {
                playPromise.then(function() {
                    // 播放成功
                }).catch(function(error) {
                    console.log('提示音播放需要用户交互:', error.message);
                });
            }
        }
    }

    /**
     * 启动定时检查
     */
    function startPeriodicCheck() {
        if (checkTimer) clearInterval(checkTimer);
        
        if (defaultOptions.checkInterval > 0 && defaultOptions.apiUrl) {
            checkTimer = setInterval(checkNewNotifications, defaultOptions.checkInterval);
        }
    }

    /**
     * 停止定时检查
     */
    function stopPeriodicCheck() {
        if (checkTimer) {
            clearInterval(checkTimer);
            checkTimer = null;
        }
    }

    /**
     * 初始化通知弹窗组件
     * @param {Object} options 配置选项
     */
    function initNotificationPopup(options) {
        $.extend(defaultOptions, options || {});
        
        // 添加CSS样式
        if (!$('#notification-popup-styles').length) {
            var styles = '<style id="notification-popup-styles">' +
                '.notification-popup {' +
                '  background-color: #fff;' +
                '  border-radius: 6px;' +
                '  box-shadow: 0 5px 15px rgba(0,0,0,0.2);' +
                '  border: 1px solid #e7eaec;' +
                '  margin-bottom: 10px;' +
                '  overflow: hidden;' +
                '  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;' +
                '}' +
                '.notification-header {' +
                '  padding: 10px 15px;' +
                '  font-weight: bold;' +
                '  color: #fff;' +
                '  display: flex;' +
                '  justify-content: space-between;' +
                '  align-items: center;' +
                '  border-bottom: 1px solid transparent;' +
                '}' +
                '.notification-title {' +
                '  font-size: 14px;' +
                '  font-weight: 600;' +
                '}' +
                '.notification-close {' +
                '  background: none;' +
                '  border: none;' +
                '  font-size: 20px;' +
                '  cursor: pointer;' +
                '  color: #fff;' +
                '  padding: 0;' +
                '  line-height: 1;' +
                '  opacity: 0.8;' +
                '}' +
                '.notification-close:hover {' +
                '  opacity: 1;' +
                '}' +
                '.notification-content {' +
                '  padding: 15px;' +
                '  font-size: 13px;' +
                '  color: #333;' +
                '  line-height: 1.5;' +
                '}' +
                '.notification-footer {' +
                '  background-color: #f9f9f9;' +
                '  border-top: 1px solid #eee;' +
                '  padding: 8px 15px;' +
                '  text-align: right;' +
                '}' +
                '.notification-action {' +
                '  text-decoration: none;' +
                '  font-size: 13px;' +
                '  font-weight: 500;' +
                '}' +
                '.notification-action:hover {' +
                '  text-decoration: underline;' +
                '}' +
                // 默认样式 (低优先级 - info)
                '.notification-info .notification-header {' +
                '  background-color: #5bc0de;' +
                '  border-bottom-color: #46b8da;' +
                '}' +
                '.notification-info .notification-action {' +
                '  color: #5bc0de;' +
                '}' +
                // 中优先级 - success
                '.notification-success .notification-header {' +
                '  background-color: #5cb85c;' +
                '  border-bottom-color: #4cae4c;' +
                '}' +
                '.notification-success .notification-action {' +
                '  color: #5cb85c;' +
                '}' +
                // 高优先级 - primary
                '.notification-primary .notification-header {' +
                '  background-color: #337ab7;' +
                '  border-bottom-color: #2e6da4;' +
                '}' +
                '.notification-primary .notification-action {' +
                '  color: #337ab7;' +
                '}' +
                // 紧急 - warning
                '.notification-warning .notification-header {' +
                '  background-color: #f0ad4e;' +
                '  border-bottom-color: #eea236;' +
                '}' +
                '.notification-warning .notification-action {' +
                '  color: #f0ad4e;' +
                '}' +
                // 立即 - danger
                '.notification-danger .notification-header {' +
                '  background-color: #d9534f;' +
                '  border-bottom-color: #d43f3a;' +
                '}' +
                '.notification-danger .notification-action {' +
                '  color: #d9534f;' +
                '}' +
                // 优先级标签
                '.notification-header::before {' +
                '  content: "通知";' +
                '  font-size: 12px;' +
                '  padding: 2px 6px;' +
                '  border-radius: 10px;' +
                '  background-color: rgba(255,255,255,0.2);' +
                '  margin-right: 8px;' +
                '}' +
                '.notification-info .notification-header::before {' +
                '  content: "普通";' +
                '}' +
                '.notification-success .notification-header::before {' +
                '  content: "中等";' +
                '}' +
                '.notification-primary .notification-header::before {' +
                '  content: "重要";' +
                '}' +
                '.notification-warning .notification-header::before {' +
                '  content: "紧急";' +
                '}' +
                '.notification-danger .notification-header::before {' +
                '  content: "立即";' +
                '}' +
                '.slideInUp {' +
                '  animation: slideInUp 0.4s ease-out;' +
                '}' +
                '.slideOutDown {' +
                '  animation: slideOutDown 0.4s ease-out;' +
                '}' +
                '@keyframes slideInUp {' +
                '  from {' +
                '    transform: translateY(100%);' +
                '    opacity: 0;' +
                '  }' +
                '  to {' +
                '    transform: translateY(0);' +
                '    opacity: 1;' +
                '  }' +
                '}' +
                '@keyframes slideOutDown {' +
                '  from {' +
                '    transform: translateY(0);' +
                '    opacity: 1;' +
                '  }' +
                '  to {' +
                '    transform: translateY(100%);' +
                '    opacity: 0;' +
                '  }' +
                '}' +
                '</style>';
            
            $('head').append(styles);
        }
        
        // 启动定时检查
        startPeriodicCheck();
        
        return {
            createNotification: createNotification,
            removeNotification: removeNotification,
            checkNewNotifications: checkNewNotifications,
            startPeriodicCheck: startPeriodicCheck,
            stopPeriodicCheck: stopPeriodicCheck
        };
    }

    // 添加到jQuery命名空间
    $.notificationPopup = {
        init: initNotificationPopup,
        create: createNotification,
        remove: removeNotification,
        check: checkNewNotifications,
        start: startPeriodicCheck,
        stop: stopPeriodicCheck
    };
})(jQuery);